//
//  ShangJiaViewController.m
//  lover-go-ios-beta
//
//  Created by liudonghuan on 14-8-29.
//  Copyright (c) 2014年 liudonghuan. All rights reserved.
//  商家页面，传入商家UUID和商家的头图片（这个在改进中）
//

#import "LGUtil.h"
#import "MapViewController.h"
#import "ShangJiaViewController.h"
#import "NSString+URLEncoding.h"
#import "WebViewController.h"
#import "TuanWebViewController.h"
#import "DataCenter.h"
@interface ShangJiaViewController ()
@end
@implementation ShangJiaViewController
-(void)loadView
{
    _appkey = @"691594651";
    _Secret = @"ad59a6b9192946a1bfdadbef4851960e";
    _DpUtil = [[DPUtil alloc]initWithAppKey:_appkey AppSecret:_Secret];
    _ShangJiaData = [[NSMutableDictionary alloc]init];
    [self dinglan];
    _waitView = [[WaitView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _ShangJiaView = [[ShangJiaView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _waitView.waitDelegate = self;
    [self setView:_ShangJiaView];
    [self.view addSubview:_waitView];
    [_waitView starttoload];
    ifshoucang = YES;
    
    UIButton* rBtn = [[UIButton alloc] initWithFrame:CGRectMake(0,0,30,30)];
    [rBtn setImage:[UIImage imageNamed:@"more_button_up.png"]forState:UIControlStateNormal];
    [rBtn setImage:[UIImage imageNamed:@"more_button_down.png"]forState:UIControlStateHighlighted];
    [rBtn addTarget:self action:@selector(shareBtnclick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightItem = [[UIBarButtonItem alloc] initWithCustomView:rBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
}
-(void)dinglan{
    UIButton * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,20, 20)];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"btn_back.png"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(dinglanBackBtn) forControlEvents:UIControlEventTouchUpInside] ;
    [backBtn setShowsTouchWhenHighlighted:YES] ;
    UIBarButtonItem *backbutton = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backbutton;
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(90, 0, 140, 30)];
    title.textAlignment = UITextAlignmentCenter;
    title.textColor = LGCOLOR_blue;
    title.text = @"商家";
    self.navigationItem.titleView = title;
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"barBG.png"] forBarMetrics:UIBarMetricsDefault];
}
-(void)dinglanBackBtn{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)retrytoload:(WaitView *)view
{
    NSDictionary *para = [NSDictionary dictionaryWithObjectsAndKeys:
                          _placeUuid,@"placeUuid",
                          nil];
    [[SVHTTPClient sharedClient] GET:findSinglePlace
                          parameters:para
                          completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error) {
                              if (error) {
                                  [view failtoload];
                              }else{
                                  id jsonObject = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:nil];
                                  [self loadData:jsonObject];
                              }
                          }];
}
-(void)shareBtnclick:(id)sender
{
    NSString *aaa;
    if (ifshoucang){
        aaa = @"收藏";
    }else{
        aaa = @"取消收藏";
    }
    
    _asheet = [[UIActionSheet alloc]initWithTitle:@"您打算？" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"分享" otherButtonTitles:aaa, nil];
    _asheet.tag =1;
    [_asheet showInView:self.view];
    
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        UIImage *_shareImg = nil;
        if (_ShangJiaView.romantip_image) {
            _shareImg = _ShangJiaView.romantip_image.image;
        }
        [LGUtil shareToSNSURL:[NSString stringWithFormat:@"%@%@%@",@"http://lover-go.com:8588/",@"lover-go/openRoute/getOriginPlaceInfo?placeUuid=",[_ShangJiaData objectForKey:@"uuid"]] title:[_ShangJiaData objectForKey:@"placeName"] img:_shareImg content:[_ShangJiaData objectForKey:@"placeName"]
                   controller:self];
    }else if (buttonIndex == 1){
        //执行收藏
        [self addtocollection];
    }
}
-(void)addtocollection{
    NSString *placeUuid = [_ShangJiaData objectForKey:@"uuid"];
    NSString *appUserUuid = [[DataCenter getSingleton].userInfo uuid];
    NSString *articleUuid = [_ShangJiaData objectForKey:@"articleName"];
    NSString *sss = [[articleUuid componentsSeparatedByString:@";"] lastObject];
    NSDictionary *para = [NSDictionary dictionaryWithObjectsAndKeys:
                          placeUuid,@"placeUuid",
                          appUserUuid,@"appUserUuid",
                          sss,@"articleUuid",
                          nil];
    
    if (appUserUuid !=nil) {
        if (ifshoucang) {
            [SVHTTPRequest GET:newaddCollection
                    parameters:para
                    completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error) {
                        if (error) {
                            [[[[UIApplication sharedApplication] delegate] window] makeToast:@"网络接连失败"
                                                                                    duration:1.0
                                                                                    position:@"center"];
                        }else{
                            NSError *jsonError = nil;
                            id jsonObject = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&jsonError];
                            int status = [[jsonObject objectForKey:@"status"]intValue];
                            if (status == 0) {
                                
                                [[[[UIApplication sharedApplication] delegate] window] makeToast:@"收藏成功"
                                                                                        duration:1.0
                                                                                        position:@"center"];
                                ifshoucang = NO;
                            }else if(status == 3){
                                
                                [[[[UIApplication sharedApplication] delegate] window] makeToast:@"再次收藏"
                                                                                        duration:1.0
                                                                                        position:@"center"];
                                ifshoucang = NO;
                            }
                            
                        }
                    }];
            
        }else{
            [SVHTTPRequest GET:newdecCoolection
                    parameters:para
                    completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error) {
                        if (error) {
                            [[[[UIApplication sharedApplication] delegate] window] makeToast:@"网络接连失败"
                                                                                    duration:1.0
                                                                                    position:@"center"];
                        }else{
                            NSError *jsonError = nil;
                            id jsonObject = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&jsonError];
                            int status = [[jsonObject objectForKey:@"status"]intValue];
                            if (status == 0) {
                                
                                [[[[UIApplication sharedApplication] delegate] window] makeToast:@"取消收藏"
                                                                                        duration:1.0
                                                                                        position:@"center"];
                                ifshoucang = YES;
                                
                            }
                            
                        }
                    }];

        }
    }else{
        [[[[UIApplication sharedApplication] delegate] window] makeToast:@"目前收藏功能只对登陆用户开放"
                                                                duration:1.0
                                                                position:@"center"];
    }
    
}
-(id)initWithDic:(NSString *)placeUuid
{
    self = [super init];
    if(self){
        _totalData = nil;
        _placeUuid = placeUuid;
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}
-(void)romantip:(id)sender
{
    NSString *yuanstring = [_ShangJiaData objectForKey:@"articleName"];
    if([yuanstring isEqualToString:@""]){
        
    }else{
        NSRange range = [yuanstring rangeOfString:@";"];
        NSString * result = [yuanstring substringFromIndex:range.location+1];
        NSString *weburl = [NSString stringWithFormat:@"%@%@",@"http://lover-go.com:8588/lover-go/article/findArticleByUuidForView?uuid=",result];
        WebViewController *wevc = [[WebViewController alloc]initWithString:weburl Title:@"浪漫攻略"];
        [self.navigationController pushViewController:wevc animated:true];
    }

}
-(void)loadImageWithUuid:(NSString *)uuid
{
    NSDictionary *para = [NSDictionary dictionaryWithObjectsAndKeys:
                          uuid,@"placeUuid",
                          nil];
    [[RequestManager getSingleton] sendRequest:findImage para:para callBack:^(id responseObj) {
        _ImageTotalData = [responseObj objectForKey:@"data"];
        //头图片
        if (_ImageTotalData.count !=0 && _ImageTotalData.count == 1  ) {//无浪漫贴士。
            _ImageData = [_ImageTotalData objectAtIndex:0];
            NSString *headimage = [NSString stringWithFormat:@"%@%@%@",imagebaseUrl,shangJiaImgSPath,[_ImageData objectForKey:@"imageUrl"]];
            _ShangJiaView.ShangJiaheadimage.imageUrl = headimage;
        }else{
            _ImageData = [_ImageTotalData objectAtIndex:0];
            NSString *headimage = [NSString stringWithFormat:@"%@%@%@",imagebaseUrl,shangJiaImgSPath,[_ImageData objectForKey:@"imageUrl"]];
            _ShangJiaView.ShangJiaheadimage.imageUrl = headimage;
            _ImageData = [_ImageTotalData objectAtIndex:1];
            NSString *romainimage = [NSString stringWithFormat:@"%@%@%@",imagebaseUrl,shangJiaImgSPath,[_ImageData objectForKey:@"imageUrl"]];
            _ShangJiaView.romantip_image.imageUrl = romainimage;
        }
    }];
    
}
-(void)refreshView:(NSMutableDictionary *)dic
{
    _ShangJiaView.romantip_title.text = @"浪漫攻略";
    _ShangJiaView.romantip_more.text = @"更多详情";
    //加载图片
    [self loadImageWithUuid:[_ShangJiaData objectForKey:@"uuid"]];
    
    //标题
    _ShangJiaView.ShangJiatitle.text =[NSString stringWithFormat:@"%@%@",@"   ",[_ShangJiaData objectForKey:@"placeName"]];
    //点击事件
    UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(romantip:)];
    [_ShangJiaView.ShangJiaromantip addGestureRecognizer:tapGesture];
    _ShangJiaView.ShangJiaromantip.userInteractionEnabled = YES;
    _ShangJiaView.romantip_context.text = [_ShangJiaData objectForKey:@"romanticReason"];
    _ShangJiaView.ShangJiaprice.itemtext.text = [[NSString alloc]initWithFormat:@"%@%@",@"人均:",[_ShangJiaData objectForKey:@"payRank"]];
    _ShangJiaView.ShangJiatime.itemtext.text = [self DataIfNull:@"openTime"];
    UITapGestureRecognizer *readtime = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(readTimeMore)];
    [_ShangJiaView.ShangJiatime addGestureRecognizer:readtime];
    _ShangJiaView.ShangJiatel.itemtext.text = [self DataIfNull:@"tel"];
    UITapGestureRecognizer *phonecall=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(makephonecall)];
    [_ShangJiaView.ShangJiatel addGestureRecognizer:phonecall];
    _ShangJiaView.ShangJiaaddress.itemtext.text = [self DataIfNull:@"detailAdress"];
    UITapGestureRecognizer *openmap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openmap)];
    [_ShangJiaView.ShangJiaaddress addGestureRecognizer:openmap];
    _ShangJiaView.ShangJiatuan.itemtext.text = [[NSString alloc]initWithFormat:@"%@",@"省钱攻略"];
    UITapGestureRecognizer *tuangou = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tuanGou)];
    [_ShangJiaView.ShangJiatuan addGestureRecognizer:tuangou];
}
-(void)tuanGou//调用大众
{
    NSString *unicodeCityStr = [NSString stringWithCString:[@"天津" UTF8String] encoding:NSUTF8StringEncoding];
    NSDictionary *para = [NSDictionary dictionaryWithObjectsAndKeys:
                          unicodeCityStr,@"city",
                          [_ShangJiaData objectForKey:@"ifTuangou"],@"business_id",
                          nil];
    
    NSString *sign = [_DpUtil serializeURL:tuangouSPath params:para];
    
    //加载一个NSURL对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:sign]];
    //将请求的url数据放到NSData对象中
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSError *error;
    NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
    
    
    NSString *dealurl = [[[weatherDic objectForKey:@"deals"] objectAtIndex:0] objectForKey:@"deal_url"];
    NSString *status = [weatherDic objectForKey:@"status"];
    if ([status isEqualToString:@"OK"]) {
        self.navigationItem.backBarButtonItem = [LGUtil getBackButton];
        TuanWebViewController *tuanV = [[TuanWebViewController alloc]initWithRealUrl:dealurl];
        [self.navigationController pushViewController:tuanV animated:YES];
    }else{
        [[[[UIApplication sharedApplication] delegate] window] makeToast:@"该商家暂无团购"
                                                                duration:1.0
                                                                position:@"center"];
    }
    
    
    
}


-(void)readTimeMore
{
    [self.view makeToast:[self DataIfNull:@"openTime"]
                duration:3.0
                position:@"top"
                   title:@"营业时间"];
}
-(NSString *)DataIfNull:(NSString *)key
{
    NSString *dataString = [[NSString alloc]initWithFormat:@"%@",[_ShangJiaData objectForKey:key]];
    if (![dataString compare:@""]) {
        dataString = @"小编正在收集此项数据中哦...";
    }
    return dataString;
}
//打开地图
-(void)openmap
{
    NSString* latStr = [[NSString alloc] initWithFormat:@"%e",[[_ShangJiaData objectForKey:@"latitude"] doubleValue]];
    NSString* lngStr =[[NSString alloc] initWithFormat:@"%e",[[_ShangJiaData objectForKey:@"longitude"] doubleValue]];
    NSString *pName = [[NSString alloc]initWithFormat:@"%@",[_ShangJiaData objectForKey:@"placeName"]];
    NSLog(@"%lf",[[_ShangJiaData objectForKey:@"latitude"] doubleValue]);
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                pName,@"address",
                                /*@"上海市",@"city",*/
                                @"baidu",@"from_map_type",
                                latStr,@"baidu_lat",
                                lngStr,@"baidu_lng",
                                /*@"浦东新区",@"region",*/ nil];
    
    
    MapViewController *mv = [[MapViewController alloc] init];
    mv.navDic = dic;
    mv.mapType = RegionNavi;
    
    [self.navigationController pushViewController:mv animated:YES];
}
//打电话
-(void)makephonecall
{
    
    UIAlertView *alertfirst = [[UIAlertView alloc]initWithTitle:@"联系商家" message:@"是否拨打商家电话" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:@"取消", nil] ;
    [alertfirst show];
    
    
}
//处理弹出框事件
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        NSString *phonecall = [NSString stringWithFormat:@"%@%@",@"tel:",[_ShangJiaData objectForKey:@"tel"]];
        if(![[UIApplication sharedApplication]openURL:[NSURL URLWithString:phonecall]] ){
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"无法打开程序" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil] ;
            [alert show] ;
        }
        
    }
    
    else {
        
    }
}
-(void)loadData:(NSDictionary*)res
{
    [_waitView removeFromSuperview];
    _totalData = [res objectForKey:@"data"];
    if (_totalData == nil) {
        return;
    }
    if (_totalData.count <= 0) {
        //这里弹一个加载数据失败的toast
        return;
    }
    _ShangJiaData = [_totalData objectAtIndex:0];
    NSString *ifHaveRomantic = [_ShangJiaData objectForKey:@"romanticReason"];
    if (![ifHaveRomantic compare:@""]) {//无浪漫攻略
        [_ShangJiaView deleteRomantic];
    }
    [self refreshView:_ShangJiaData];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"商家"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"商家"];
}

@end
